#include "stdio.h"
#include "string.h"

//定义双向链表节点结构体
struct list_node {

    int data;
    struct list_node *pre;
    struct list_node *next;
};

struct list_node *head = NULL;


//初始化链表
static struct list_node *init_list(void)
{
    //生成头节点
    struct list_node *head = (struct list_node *)malloc(sizeof(struct list_node));
    head->next = NULL;
    head->pre  = NULL;
    head->data  = 1;

    struct list_node *p = head;

    for (int i = 2; i <= 5; i++) {

        struct list_node *tmp = (struct list_node *) malloc(sizeof(struct list_node));

        tmp->next = NULL;
        tmp->data = i;

        p->next = tmp; 
        tmp->pre = p;

        p = p->next;
    }

    return head;
}


//插入一个节点，offs：插入位置， val：插入的值
static struct list_node *insert_list(struct list_node *head, int offs, int val)
{
    int i = 0;
    struct list_node *curr = head;
    struct list_node *pre  = head;

    struct list_node *new = (struct list_node *)malloc(sizeof(struct list_node)); 
    new->data = val;
    new->next = NULL;
    new->pre  = NULL;

    //插入的是表头
    if (offs == 1) {
        new->next = head;
        head->pre = new;
        head = new;
    } else {

        //找到插入的节点        
        for (int i = 1; i < offs - 1; i++) {
            if (pre == NULL) {  //超出长度
                return head;
            }
            pre = pre->next;
        }

        //插入的是尾部
        if (pre->next == NULL) {
            
            pre->next = new;
            new->pre  = pre;

        } else {  //插入的是中间

            new->next = pre->next;
            pre->next = new;
            new->pre  = pre;
        }
    }

    return head;
}


//打印链表
static void print_list(struct list_node *head)
{
    struct list_node *curr = head;

    while (curr != NULL) {
        printf("%d ", curr->data);
        curr = curr->next;
    }
}



//测试
void double_list_test(void)
{
    struct list_node *p;

    printf("\r\ninit_list: \r\n");
    p = init_list();
    head = p;
    print_list(p);

    printf("\r\ninsert_list: \r\n");
    p = insert_list(head, 1, 22);
    print_list(p);
    printf("\r\n");


}